<template>
  <el-form ref="basicInformationForm" :model="basicInformationForm" label-width="99px" :hide-required-asterisk="true">
    <Form :form="basicInformationForm" :ActivityAreaList="AreaList" :parentPlanName="Originalarray"></Form>
    <el-row style="margin-top: 20px">
      <el-col :span="8">
        <el-form-item label="" prop="remark">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </el-form-item></el-col>
    </el-row>
  </el-form>
</template>
<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';
import {
  getLists,
  insertData,
  deletelist,
  ModifierList,
} from "../../api/Genericmethods/GeneralQuery.js";
import Form from "./components/form.vue";
// import Concretestep from "./concretestep.vue";
export default {
  // eslint-disable-next-line vue/no-unused-components
  components: { Form },
  props: {},
  data() {
    return {
      // 表单参数
      basicInformationForm: {
        AccidentArea: "", //事故发生区域
        AccidentPoint: "", //事故发生设备
        AccidentRisk: "", //事故风险
        AccidentScope: "", //事故发生范围（全厂/某产线）
        AccidentType: [], //事故类型
        AccidentWarnDeal: "", //事故预警措施
        AccidentWarnSign: "", //事故预警征兆
        Gradename: "班级组", //等级名称
        Notes: "", //注意事项
        PlanName: "", //预案名称
        PlanType: "现场处置方案", //预案类型
        PossibleEffectScope: "", //可能影响范围
        PossibleMatter: "", //可能衍生事故
        PossibleOccurArea: "", //可能发生区域/地点
        PossibleSeverity: "", //可能严重程度
        PossibleTime: "", //可能发生时间
        Possiblelinkage: [], //可能联动范围
        Responselevel: "III级", //响应等级
      },
      AreaList: [
        {
          zoneofaction: "",
          AccidentArea: "",
          MeasureName: "",
          // 左边的选中状态
          currentDisposal: 0,
          Disposalserialnumber: [
            {
              DealStep: "",
              divContents: [
                {
                  DealExecutor: "",
                  contents: [{ value: "" }, { value: "" }],
                },
              ],
            },
          ], // 存储处置信息的数组
        },
      ],
      Originalarray: "",
    };
  },
  // 计算属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 方法集合
  methods: {
    // 取消按钮
    cancel() {
      this.$router.go(-1);
      this.$refs["basicInformationForm"].resetFields();
    },
    // 提交按钮
    submitForm() {
      this.$refs["basicInformationForm"].validate((valid) => {
        console.log(this.basicInformationForm);
        if (valid) {
          // 具体步骤添加
          const PlanName = this.basicInformationForm.PlanName;
          const PlanType = this.basicInformationForm.PlanType;
          const AreaList = this.AreaList;
          const sqllist =
            '`PlanType`,`PlanName`,`AccidentArea`,`AccidentPoint`,`DealCode`,`DealStep`,`MeasureName`,`DealExecutor`,`DealContent1`,`DealContent2`,`DealContent3`,`DealContent4`,`DealContent5`,`DealContent6`,`DealContent7`,`DealContent8`,`DealContent9`,`DealContent10`,`DealContent11`,`DealContent12`,`DealContent13`,`DealContent14`,`DealContent15`,`DealContent16`,`DealContent17`,`DealContent18`,`DealContent19`,`DealContent20`';
          const insertSql = [];
          for (let i = 0; i < AreaList.length; i++) {
            const area = AreaList[i];
            let AccidentArea = "";
            let AccidentPoint = "";
            if (area.zoneofaction === "设备") {
              AccidentPoint = area.AccidentArea;
            } else if (area.zoneofaction === "区域") {
              AccidentArea = area.AccidentArea;
            }
            for (let j = 0; j < area.Disposalserialnumber.length; j++) {
              const disposal = area.Disposalserialnumber[j];
              for (let k = 0; k < disposal.divContents.length; k++) {
                const content = disposal.divContents[k];
                const dealCode = j + 1;
                // let sql = `INSERT INTO IMP."EmergPlan_SiteRspMrs_Deal" ("PlanType","PlanName","AccidentArea","AccidentPoint","DealCode","DealStep","MeasureName","DealExecutor","DealContent1","DealContent2","DealContent3","DealContent4","DealContent5","DealContent6","DealContent7","DealContent8","DealContent9","DealContent10") VALUES (`;
                let sql = `'${PlanType}','${PlanName}','${AccidentArea}','${AccidentPoint}','${dealCode}','${disposal.DealStep}','${area.MeasureName}','${content.DealExecutor}'`;
                for (let l = 0; l < 20; l++) {
                  const value = content.contents[l]?.value || ""; // 如果值为 undefined 或 null，则设置为空字符串
                  sql += `,'${value}'`;
                }
                // 检查新内容的长度是否超过了限制
                // if (content.contents[k].value.length > 4000) {
                //   this.$message.error("内容长度超过限制");
                //   return;
                // }
                insertSql.push(sql);
              }
            }
          }
          // 创建一个空数组，用于存储所有请求的Promise对象
          const promises = [];
          for (let index = 0; index < insertSql.length; index++) {
            const element = insertSql[index];
            // 将每个请求添加到promises数组中
            const promise = insertData(
              "EmergPlan_SiteRspMrs_Deal",
              sqllist,
              element
            )
              .then((res) => {
                if (res.data.code === 1) {
                  this.OperationLog(res, this.$route.meta.title);
                } else {
                  throw new Error(res.data.message);
                }
              })
              .catch((err) => {
                console.log(err);
                throw err;
              });
            promises.push(promise);
          }
          // 使用Promise.all()等待所有请求完成
          Promise.all(promises)
            .then(() => {
              this.$modal.msgSuccess("具体步骤新增成功");
              // 所有请求都成功完成
              this.$router.go(-1);
            })
            .catch((err) => {
              // 请求中有一个或多个失败
              this.$message.error(err);
            });
          // 基本信息添加操作
          const fieldlist = Object.keys(this.basicInformationForm)
            .map((field) => `\`${field}\``)
            .join(",");
          const result = `${Object.values(this.basicInformationForm)
            .map((value) => `'${value}'`)
            .join(",")}`;
          insertData("EmergPlan_SiteRspMrs", fieldlist, result)
            .then((res) => {
              if (res.data.code === 1) {
                this.$modal.msgSuccess("基本信息新增成功");
              } else {
                this.$message.error(res.data.message);
              }
              this.OperationLog(res, this.$route.meta.title);
            })
            .catch((err) => {
              console.log(err);
            });
        } else {
          return this.$message.error(false);
        }
      });
    },
    OperationLog(res, title) {
      // INSERT INTO IMP."OperationLogList" ("timestamp","SQL","TIP","code","message","title") VALUES ('1','2','3','4','6','7')
      const timestamp = "'" + res.data.timestamp + "'";
      const SQL = "'" + res.getAllParams.SQL.replace(/'/g, "\\'") + "'";
      const TIP = "'" + res.getAllParams.TIP + "'";
      const code = "'" + res.data.code + "'";
      const message = "'" + res.data.message + "'";
      const titles = "'" + title + "'";
      const parameter = "OperationLogList";
      const fieldlist = '`timestamp`,`SQL`,`TIP`,`code`,`message`,`title`';
      const result = `${timestamp}, ${SQL}, ${TIP}, ${code}, ${message}, ${titles}`;
      insertData(parameter, fieldlist, result);
    },
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.Originalarray = this.$route.query.data
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() { },
  beforeCreate() { },
  beforeMount() { },
  beforeUpdate() { },
  updated() { },
  beforeDestroy() { },
  destroyed() { },
  activated() { },
};
</script>
<style lang="scss" scoped></style>
